import { api } from '@/api'
import { login } from '@/utils'
import router from '@/router'
import { asyncRoutesMap } from '@/router/config'
const auth = {
  state: {
    token: login.getToken(),
    userInfo: {}
  },
  mutations: {
    SET_TOKEN(state, token) {
      console.log('token:', token)
      state.token = token
    },
    SET_COOKIE(state, data) {
      console.log('data, ', data)
    },
    SET_USER_INFO(state, data) {
      state.userInfo = data;
    },
    REMOVE_TOKEN(state) {
      login.removeToken()
    }
  },
  actions: { // 首字母大写驼峰
    GetLogin({ commit }, data) {
      // 请求登陆接口
      return new Promise((resolve, reject) => {
        api.getLogin()
        .then(res => {
          console.log('res:', res)
          resolve() // 告诉页面我成功了
          login.setToken(res.data.token) // 存储token
          commit('SET_TOKEN', res.data.token) // 提交给mutation
        }).catch(err => {
          reject(err)
        })
      })
    },
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        api.getUserInfo().then(result => {
          console.log('用户信息', result)
          resolve(result.data)
          // 过滤函数
          function filterAsyncRouterMap(config, userid = 2) {
            const routerBrr = config.filter(item => item.meta.userId.indexOf(userid) > -1);
            config.forEach(item => {
              // cßnsole.log('item: ', item.meta.userId.includes(userid))
              if (item.meta.userId.includes(userid)) {
                // console.log(item.children, 'children')
                item.children && item.children.length && (item.children = filterAsyncRouterMap(item.children))
              }
            })
            console.log(routerBrr, 'config')
            return routerBrr;
          }
          const it = filterAsyncRouterMap(asyncRoutesMap)
          console.log('it: ', it)
          // addRouter
          router.addRoutes(it);
          commit('SET_USER_INFO', result)
        }).catch(err => {
          reject(err)
        })
      })
    },
    LoginOut({ commit }, data) {
      return new Promise((resolve, reject) => {
        resolve('success')
        commit('REMOVE_TOKEN')
      }).catch((err) => {
        console.log('err', err)
      })
    }
  }
}
export { auth }
